package top.mcwebsite.playandroid.business.me.impl.main.vm

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import top.mcwebsite.playandroid.common.user.api.IUserService
import top.mcwebsite.playandroid.common.user.api.model.UserData
import top.mcwebsite.playandroid.common.user.api.model.UserInfo
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class MeViewModel : BaseViewModel<MeIntent, MeUiState, MeUiEffect>(
    MeUiState()
) {
    private val userService = ServiceManager.getService<IUserService>()

    private var userInfo: UserData? = null

    init {
        onEach(MeUiState::isLogin) {
            if (it) {
                setUiState {
                    userService.getCachedUserData()?.let {
                        userInfo = it
                        copy(userAvatar = it.userInfo.icon, username = it.userInfo.username, coinCount = it.coinInfo.coinCount)
                    } ?: this
                }
                viewModelScope.launch {
                    val userData = userService.getUserInfo()
                    userInfo = userData
                    setUiState {
                        copy(
                            userAvatar = userData.userInfo.icon,
                            username = userData.userInfo.username,
                            level = userData.coinInfo.level,
                            rank = userData.coinInfo.rank,
                            coinCount = userData.coinInfo.coinCount,
                        )
                    }
                }
            }
        }
        viewModelScope.launch {
            userService.isLoginFlow().collect {
                setUiState {
                    copy(isLogin = it)
                }
            }
        }
    }

    override fun handleIntent(intent: MeIntent) {
        when (intent) {
            is MeIntent.LoginIntent -> {
                sendUiEffect(MeUiEffect.NavigateToLoginEffect)
            }
            is MeIntent.GoUserCoinPageIntent -> {
                userInfo?.let {
                    sendUiEffect(MeUiEffect.NavigateToUserCoinPageUiEffect(coinInfo = it.coinInfo))
                }
            }
            is MeIntent.GoSettingsPageIntent -> {
                sendUiEffect(MeUiEffect.NavigationToSettingsPageUiEffect)
            }
        }
    }
}


sealed class UserHomePageTab(val name: String) {
    object CollectionArticle : UserHomePageTab("收藏文章")
    object CollectionWebsite : UserHomePageTab("收藏文章")
    object ShareArticle : UserHomePageTab("分享文章")
    object ShareWebsite : UserHomePageTab("分享网站")
}

internal val homePageTabs = listOf(
    UserHomePageTab.CollectionArticle,
    UserHomePageTab.ShareArticle,
    UserHomePageTab.CollectionWebsite,
    UserHomePageTab.ShareWebsite
)